package com.taotao.config;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 自动加载限流规则
 */
@Component
@Slf4j
public class SentinelApplicationRunner implements ApplicationRunner {
    /**
     * 限流资源名称 getSentinelThreads
     */
    private static final String SENTINE_KEY_SENTINELTHREADS = "getSentinelThreads";
    /**
     * 限流资源名称 getSentinelQps
     */
    private static final String SENTINE_KEY_GETSENTINELQPS = "getSentinelQps";

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<FlowRule> rules = new ArrayList<FlowRule>();
        // 新增限流规则1
        FlowRule rule1 = new FlowRule();
        rule1.setResource(SENTINE_KEY_SENTINELTHREADS);
        // QPS控制在2以内
        rule1.setCount(1);
        // QPS限流
        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule1.setLimitApp("default");
        rules.add(rule1);

        FlowRule rule2 = new FlowRule();
        // 创建限流资源
        rule2.setResource(SENTINE_KEY_GETSENTINELQPS);
        // QPS控制在2以内
        rule2.setCount(2);
        // QPS限流
        rule2.setGrade(RuleConstant.FLOW_GRADE_THREAD);
        //限流应用default
        rule2.setLimitApp("default");
        //添加该限流规则
        rules.add(rule2);
        FlowRuleManager.loadRules(rules);
        log.info(">>>限流服务接口配置加载成功>>>");
    }
}
